import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../layout/Home.vue'
import local from '../utils/locl.js'
/* 引入抽出去的路由 */
import cvRouter from './cvRouter'

Vue.use(VueRouter)

const routes = [
  // 默认目录
  {
    path: '/',
    redirect: '/home'
  },
  // 首页
  {
    path: '/home',
    component: Home,
    mete: { name: '后台' },
    redirect: '/frist',
    children: [
      // 后台首页内容
      {
        path: '/frist',
        meta: { name: '首页' },
        component: () =>
          import(/* webpackChunkName: "frist" */ '../views/first/index.vue')
      }
    ]
  },
  // 登录路由
  {
    path: '/login',
    component: () =>
      import(/* webpackChunkName: "Login" */ '../views/Login.vue')
  },
  // 404
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: () => import(/* webpackChunkName: "404" */ '../views/404.vue')
  }
]
// component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
const router = new VueRouter({
  routes
})

/* 根据不同登陆的角色，来确定将来展示的路由信息------------------------------------------ */
getlogin()
/* ---1--- 主体 */
export function getlogin() {
  // 凭借登录的管理员的信息
  const role = local.get('role')
  if (!role) return
  // console.log(role)
  // 承包出去，过滤部分  cvRouter.routes它是抽出去的路由
  const fillRoute = jsRoute(cvRouter.routes, role)
  // .log(fillRoute, '-------')
  // ---4---合并到主路由  routes[1].children它就是主路由上按索引的第一个，让它回归
  routes[1].children = fillRoute
  router.addRoutes([routes[1]])

  const meun = meunRouter(fillRoute)
  // console.log(meun, '====')
  local.set('meun', JSON.stringify(meun))
}
/* ---5---菜单的计算 */
function meunRouter(fillRoute) {
  return fillRoute.filter(item => {
    if (item.isVisible) {
      if (item.children) {
        item.children = meunRouter(item.children)
      }
      return true
    } else {
      return false
    }
  })
}
/* ---2---计算过滤  参数 arr=cvRouter.routes  role=role */
function jsRoute(arr, role) {
  return arr.filter(item => {
    // 承包出去鉴定权限
    if (jianQuan(item, role)) {
      if (item.children) {
        item.children = jsRoute(item.children, role)
      }
      return true
    } else {
      return false
    }
  })
}
/* ---3---鉴定权限 */
function jianQuan(obj, role) {
  if (obj.meta && obj.meta.role) {
    return obj.meta.role.includes(role)
  } else {
    return true
  }
}

// 点击面包屑时，有多余的地址
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
// 导航守卫，目的是不允许未登录的用户进入路由页面
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
